<template>
  <div class="app-container" v-loading="loading">
    <el-form ref="form" :model="form" label-width="80px" label-position="top">

      <div class="card-wrap flex-column justify-end card-padding">
<!--        <el-row :gutter="30">-->
<!--          <el-col :span="8">-->
<!--            <el-form-item label="额度编号:" prop="calcSchemeCode"  style="display: inline-block !important;">-->
<!--                <span style="color: #1890ff;cursor: pointer;" @click="goQurtaApplyDetail"> {{ ruleData.calcSchemeCode || '&#45;&#45;' }}</span>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--        </el-row>-->
        <el-descriptions>
          <el-descriptions-item label="额度申请">
            <span style="color: #1890ff;cursor: pointer;" @click="goQurtaApplyDetail"> {{ ruleData.calcSchemeCode || '--' }}</span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="card-wrap flex-column justify-end card-padding" v-if="ruleData.customerType==1">
        <el-row :gutter="30">
          <el-col :span="8">
            <el-form-item label="客户婚姻状况:" prop="customer.maritalStatus" style="width: 70%" required
                          :rules="{ required:ruleData.customerType=1, message: '请选择婚姻状况', trigger: 'change' }">
              <el-select v-model="form.customer.maritalStatus" clearable style="width: 100%" placeholder="请选择婚姻状况">
                <template v-for="dict in dict.type.marital_status">
                  <el-option :label="dict.label" :value="dict.value" :key="dict.value"></el-option>
                </template>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </div>

      <CommonContainer title="买受人信息" v-if="ruleData.isItARentalPurchase == 1">
        <el-row :gutter="30">
          <el-col :span="8">
            <el-form-item label="买受人:" prop="vendeeId" required
                          :rules="{ required:ruleData.isItARentalPurchase=1, message: '请选择买受人', trigger: 'change' }">
              <el-select v-model="form.vendeeId" filterable placeholder="请选择买受人" style="width: 70%" @change="changeVendee">
                <el-option v-for="vendee in vendeeList" :key="vendee.customerId" :label="vendee.vendeeName" :value="vendee.customerId"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <template v-if="form.vendeeId && currentVendeeObj">
            <el-col :span="8">
              <el-form-item label="类型:" prop="customerTypeCode">
                <el-select v-model="currentVendeeObj.customerTypeCode" placeholder="选择完买受人自动带出" style="width: 100%" disabled>
                  <el-option v-for="dict in dict.type.customer_type" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="8" v-if="currentVendeeObj.customerTypeCode == 2">
              <el-form-item label="统一社会信用代码:" prop="vendeeCode">
                <el-input v-model="currentVendeeObj.vendeeCode" placeholder="选择完买受人自动带出" disabled></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8" v-if="currentVendeeObj.customerTypeCode == 1">
              <el-form-item label="身份证号码/护照号码" prop="idCard">
                <el-input v-model="currentVendeeObj.idCard" placeholder="选择完买受人自动带出" disabled></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8" v-if="currentVendeeObj.customerTypeCode == 2">
              <el-form-item label="法定代表人/负责人:" prop="vendeeResponsibleName">
                <el-input v-model="currentVendeeObj.vendeeResponsibleName" placeholder="选择完买受人自动带出" disabled></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="通讯地址:" prop="vendeeAddress">
                <el-input v-model="currentVendeeObj.vendeeAddress" placeholder="选择完买受人自动带出" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8" v-if="currentVendeeObj.customerTypeCode == 2">
              <el-form-item label="联系人:" prop="vendeePerson">
                <el-input v-model="currentVendeeObj.vendeePerson" placeholder="选择完买受人自动带出" disabled></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8">
              <el-form-item label="联系电话:" prop="vendeePhone">
                <el-input v-model="currentVendeeObj.vendeePhone" placeholder="选择完买受人自动带出" disabled></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8" v-if="currentVendeeObj.customerTypeCode == 2">
              <el-form-item label="电子邮箱:" prop="vendeeMail">
                <el-input v-model="currentVendeeObj.vendeeMail" placeholder="选择完买受人自动带出" disabled></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="8" v-if="currentVendeeObj.customerTypeCode == 2">
              <el-form-item label="传真:" prop="vendeeFax">
                <el-input v-model="currentVendeeObj.vendeeFax" placeholder="选择完买受人自动带出" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="附件:" prop="templateName">
                <image-common v-model="currentVendeeObj.annexOss" disabled :up-type="2"></image-common>
              </el-form-item>
            </el-col>
          </template>


        </el-row>
      </CommonContainer>

      <CommonContainer v-if="needBasicData||ruleData.needGuarantor==1" title="基础资料">
        <div>

          <el-form-item v-for="fileItem in ruleData.basicData" :key="fileItem.id" :label="`${fileItem.dataName}:`" required>
            <image-common
                v-model="fileItem.files"
                :limit="fileItem.dataNum"
                :file-type="fileItem.dataFormat.split(',')"
                :file-size="fileItem.dataSize"
                is-show-tip
                isVerifyFileType
                :up-type="2"
                info="上传附件"
            >
            </image-common>
          </el-form-item>
          <el-form-item v-if="ruleData.needGuarantor==1" label="担保人信息:" required>
            <Guarantors ref="guarantors" :guarantorsEcho="guarantors" :need-guarantor="ruleData.needGuarantor"></Guarantors>
          </el-form-item>

        </div>

      </CommonContainer>

      <CommonContainer v-if="needChooseOneData" title="择一提供资料">
        <el-radio-group style="margin-top: 10px" v-model="currentChooseOne">
          <el-radio v-for="fileItem in ruleData.chooseOneData" :key="fileItem.id" :label="fileItem">{{ fileItem.dataName }}</el-radio>
        </el-radio-group>
        <div style="margin-top: 15px">
          <el-form-item :label="`${currentChooseOne.dataName}:`" required>
            <image-common
                v-model="currentChooseOne.files"
                :limit="currentChooseOne.dataNum"
                :file-type="currentChooseOne.dataFormat.split(',')"
                :file-size="currentChooseOne.dataSize"
                is-show-tip
                :up-type="2"
                isVerifyFileType
                info="上传附件"
            >
            </image-common>
          </el-form-item>
        </div>
      </CommonContainer>

      <CommonContainer v-if="needSelectiveData || ruleData.needGuarantor==3" title="可选择性资料">
        <div>
          <el-form-item v-for="fileItem in ruleData.selectiveData" :key="fileItem.id" :label="`${fileItem.dataName}:`">
            <image-common
                v-model="fileItem.files"
                :limit="fileItem.dataNum"
                :file-type="fileItem.dataFormat.split(',')"
                :file-size="fileItem.dataSize"
                is-show-tip
                :up-type="2"
                isVerifyFileType
                info="上传附件"
            >
            </image-common>
          </el-form-item>
          <el-form-item v-if="ruleData.needGuarantor==3" label="担保人信息:">
            <Guarantors ref="guarantors" :guarantorsEcho="guarantors" :need-guarantor="ruleData.needGuarantor"></Guarantors>
          </el-form-item>
        </div>
      </CommonContainer>


      <div class="card-wrap flex justify-end card-padding">
        <el-button @click="back">取消</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">提交信审</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import Guarantors from "@/views/letterReview/order/components/Guarantors.vue";
import * as creditApplyApi from "@/api/letterReview/creditReviewApply"
import {getVendeeList} from "@/api/letterReview/order";

export default {
  name: 'AddLetterReview',
  dicts: ['marital_status', 'credit_chooseone_filetype', 'customer_type'],
  components: {
    Guarantors
  },
  data() {
    return {
      loading: false,
      buttonLoading: false,
      //当前选中的择一提供资料
      currentChooseOne: null,
      //信审资料规则
      ruleData: {},
      form: {
        vendeeId: null,//买受人id
        id: this.$route.query.id,
        customer: {
          maritalStatus: null,
        },
        guarantors: [],
        files: [],
      },
      needBasicData: false,
      needChooseOneData: false,
      needSelectiveData: false,
      //回显的担保人
      guarantors: null,
      //买受人列表
      vendeeList: [],
      //当前买受人
      currentVendeeObj: null,
    };
  },
  mounted() {
    // this.getSubmitRules()
    this.fetchData()
  },
  methods: {
    fetchData(){
      this.loading=true
      this.getSubmitRules().then(res1=>{
        this.ruleData=res1
        if (this.ruleData.basicData && this.ruleData.basicData.length > 0) {
          this.needBasicData = true
          this.ruleData.basicData = this.ruleData.basicData.map(item => {
            this.$set(item, 'files', null)
            return item
          })
        }
        if (this.ruleData.chooseOneData && this.ruleData.chooseOneData.length > 0) {
          this.needChooseOneData = true
          this.ruleData.chooseOneData = this.ruleData.chooseOneData.map(item => {
            this.$set(item, 'files', null)
            return item
          })
          this.currentChooseOne = this.ruleData.chooseOneData[0]
        }

        if (this.ruleData.selectiveData && this.ruleData.selectiveData.length > 0) {
          this.needSelectiveData = true
          this.ruleData.selectiveData = this.ruleData.selectiveData.map(item => {
            this.$set(item, 'files', null)
            return item
          })
        }
        if(this.ruleData.isItARentalPurchase == 1){
          return this.getVendeeList(this.ruleData.customerId);
        }
      }).then(res2=>{
        if (res2){
          this.vendeeList = res2;
        }
        //如果是重新提交则获取回显信息
        if(this.$route.query.type == 2){
          return this.getResubmitData()
        }
      }).then(res3=>{
        if (res3){
          console.log('回显数据---', res3)
          const echoData= res3;
          this.form.vendeeId = echoData?.vendeeId
          if (this.form.vendeeId) {
            this.changeVendee(this.form.vendeeId);
            // this.currentVendeeObj = this.vendeeList.find((item) => {
            //   return item.customerId == this.form.vendeeId
            // })
          }
          this.form.customer.maritalStatus = echoData.maritalStatus
          this.guarantors = echoData.guarantor;
          if (this.needBasicData) {
            this.ruleData.basicData = echoData.basicData
          }
          if (this.needChooseOneData) {
            this.currentChooseOne = echoData.chooseOneData[0];
            this.ruleData.chooseOneData = this.ruleData.chooseOneData.map((item) => {
              if (this.currentChooseOne.id == item.id) {
                item = this.currentChooseOne;
              }
              return item
            })
          }
          if (this.needSelectiveData) {
            if (echoData.selectiveData && echoData.selectiveData.length > 0) {
              this.ruleData.selectiveData = this.ruleData.selectiveData.map(item => {
                echoData.selectiveData.forEach(echoItem => {
                  if (item.id == echoItem.id) {
                    item = echoItem
                  }
                })
                return item
              })
            }
          }
        }

      }).finally(f=>{
        this.loading=false
      })
    },
    //获取规则
    getSubmitRules() {
      return new Promise((resolve, reject)=>{
        creditApplyApi.getSubmitRules(this.form.id).then(res => {
          resolve(res.data);
        })
      })

    },
    //根据客户id查询买受人信息
    getVendeeList(customerId) {
      return new Promise((resolve, reject)=>{
        getVendeeList({
          customerId: customerId,
        }).then(res => {
          resolve(res.data);
        })
      })
    },

    //重新提交信审回显
    getResubmitData() {
      return new Promise((resolve, reject) => {
        creditApplyApi.getResubmitData(this.$route.query.applicationNo).then(res => {
            resolve(res.data)
        })
      })
    },
    //查看额度申请详情
    goQurtaApplyDetail() {
      if (this.checkPermi(['quota:apply:list:look'])) {
        this._toPage({
          name: 'ApplyDetails',
          query: {
            calcSchemeId: this.ruleData.calcSchemeId
          }
        })
      } else {
        this.$message.warning('无权限')
      }
    },
    //选择买受人
    changeVendee(val) {
      this.currentVendeeObj = this.vendeeList.find((item) => {
        return item.customerId == val
      })
    },
    submitForm() {
      let resultFiles = []
      if (this.needBasicData) {
        if (this.ruleData.basicData.some((val) => val.files == null || val.files == '')) {
          this.$message.error('基础资料为必填项,请完善')
          return
        } else {
          this.ruleData.basicData.forEach((item) => {
            const obj = {
              fileConfigId: item.id,
              fileUrl: item.files
            }
            resultFiles.push(obj)
          })
        }
      }
      this.form.guarantors = this.$refs?.guarantors?.saveForm();
      //担保人校验
      if (this.ruleData.needGuarantor == 1&&this.form.guarantors == null) {
          return;
      }
      console.log('guarantors', this.form.guarantors)

      if (this.needChooseOneData) {
        console.log('333')
        if (this.currentChooseOne.files == null || this.currentChooseOne.files == '') {
          this.$message.error('请上传择一提供资料')
          return
        } else {
          const obj = {
            fileConfigId: this.currentChooseOne.id,
            fileUrl: this.currentChooseOne.files
          }
          resultFiles.push(obj)
        }
      }
      if (this.needSelectiveData) {
        this.ruleData.selectiveData.forEach((item) => {
          if (!this.isNull(item.files)) {
            const obj = {
              fileConfigId: item.id,
              fileUrl: item.files
            }
            resultFiles.push(obj)
          }
        })
      }
      this.form.files = resultFiles;
      console.log('最终表单---', this.form)
      this.buttonLoading = true
      this.$refs["form"].validate(valid => {
        if (valid) {
          creditApplyApi.submitForCreditReview(this.form).then(res => {
            this.$message.success('提交成功')
            this.back()
          }).finally(() => {
            this.buttonLoading = false
          })
        }
      });


    },
    back() {
      this.$router.back()
      this.$store.dispatch('tagsView/delView', this.$route)
    }
  }
};
</script>


<style lang="scss" scoped>
::v-deep .el-form--label-top .el-form-item__label {
  padding: 0;
}

.el-form-item {
  margin-bottom: 15px;
}


</style>
